﻿using System.Globalization;
using System.IO;

namespace XYAC.Framework.MonitorTireMaterialOnline.DataExporter
{
    public enum Section
    {
        None,
        Points,
        MeasureKeys,
        TypeName,
        ID,
        XReference,
        Keys
    }

    public class DataFileParser
    {
        public static DataFile LoadFromFile(string filePath)
        {
            if (!File.Exists(filePath))
                throw new FileNotFoundException($"文件未找到: {filePath}");

            DataFile dataFile = new DataFile();
            Section currentSection = Section.None;

            using (StreamReader reader = new StreamReader(filePath))
            {
                string line;
                bool isFirstLine = true;

                while ((line = reader.ReadLine()) != null)
                {
                    line = line.Trim();

                    // 跳过空行
                    if (string.IsNullOrEmpty(line))
                        continue;

                    // 检查是否为段落标题
                    if (line.StartsWith("[") && line.EndsWith("]"))
                    {
                        string sectionName = line.Substring(1, line.Length - 2);
                        switch (sectionName)
                        {
                            case "MeasureKeys":
                                currentSection = Section.MeasureKeys;
                                break;
                            case "TypeName":
                                currentSection = Section.TypeName;
                                break;
                            case "ID":
                                currentSection = Section.ID;
                                break;
                            case "XReference":
                                currentSection = Section.XReference;
                                break;
                            case "Keys":
                                currentSection = Section.Keys;
                                break;
                            default:
                                currentSection = Section.None;
                                break;
                        }
                        continue;
                    }

                    // 解析内容
                    switch (currentSection)
                    {
                        case Section.None:
                            if (isFirstLine)
                            {
                                // 第一行是 FileInertiaWidth
                                if (float.TryParse(line, NumberStyles.Any, CultureInfo.InvariantCulture, out float inertiaWidth))
                                {
                                    dataFile.FileInertvaWidth = inertiaWidth;
                                }
                                else
                                {
                                    throw new FormatException("无法解析 FileInertiaWidth");
                                }
                                isFirstLine = false;
                            }
                            else
                            {
                                // 默认认为是 [Points] 区域
                                if (line.StartsWith("[Points]"))
                                {
                                    currentSection = Section.Points;
                                    continue;
                                }

                                // 或者直接从第二行开始默认为 [Points]
                                currentSection = Section.Points;
                                // 继续处理当前行作为 Points
                            }
                            goto case Section.Points;

                        case Section.Points:
                            // 解析 Points 数据，格式: Index\tValue1\tValue2
                            //var pointParts = line.Split(new[] { '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                            //if (pointParts.Length >= 3)
                            //{
                            //    if (int.TryParse(pointParts[0], out int index) &&
                            //        float.TryParse(pointParts[1], NumberStyles.Any, CultureInfo.InvariantCulture, out float val1) &&
                            //        float.TryParse(pointParts[2], NumberStyles.Any, CultureInfo.InvariantCulture, out float val2))
                            //    {
                            //        dataFile.Points.Add(new Point
                            //        {
                            //            Index = index,
                            //            X = val1,
                            //            Y = val2
                            //        });
                            //    }
                            //    else
                            //    {
                            //        throw new FormatException($"无法解析 Points 行: {line}");
                            //    }
                            //}
                            break;

                        case Section.MeasureKeys:
                            // 解析 MeasureKeys 数据，格式: Coordinate\tValue
                            var measureParts = line.Split(new[] { '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                            if (measureParts.Length >= 2)
                            {
                                if (double.TryParse(measureParts[0], NumberStyles.Any, CultureInfo.InvariantCulture, out double mCoord) &&
                                    double.TryParse(measureParts[1], NumberStyles.Any, CultureInfo.InvariantCulture, out double mValue))
                                {
                                    dataFile.MeasureKeys.Add(new MeasureKey
                                    {
                                        Coordinate = mCoord,
                                        Value = mValue
                                    });
                                }
                                else
                                {
                                    throw new FormatException($"无法解析 MeasureKeys 行: {line}");
                                }
                            }
                            break;

                        case Section.TypeName:
                            // 解析 TypeName，假设 TypeName 只有一行
                            dataFile.TypeName = line;
                            currentSection = Section.None;
                            break;

                        case Section.ID:
                            // 解析 ID，假设 ID 只有一行
                            if (int.TryParse(line, out int id))
                            {
                                dataFile.ID = id;
                            }
                            else
                            {
                                throw new FormatException("无法解析 ID");
                            }
                            currentSection = Section.None;
                            break;

                        case Section.XReference:
                            // 解析 XReference，假设 XReference 只有一行
                            if (double.TryParse(line, NumberStyles.Any, CultureInfo.InvariantCulture, out double xRef))
                            {
                                dataFile.XReference = xRef;
                            }
                            else
                            {
                                throw new FormatException("无法解析 XReference");
                            }
                            currentSection = Section.None;
                            break;

                        case Section.Keys:
                            // 解析 Keys 数据，格式: Coordinate\tValue
                            var keyParts = line.Split(new[] { '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                            if (keyParts.Length >= 2)
                            {
                                if (double.TryParse(keyParts[0], NumberStyles.Any, CultureInfo.InvariantCulture, out double kCoord) &&
                                    double.TryParse(keyParts[1], NumberStyles.Any, CultureInfo.InvariantCulture, out double kValue))
                                {
                                    dataFile.StableKeys.Add(new StableKeys
                                    {
                                        Coordinate = kCoord,
                                        Value = kValue
                                    });
                                }
                                else
                                {
                                    throw new FormatException($"无法解析 Keys 行: {line}");
                                }
                            }
                            break;

                        default:
                            // 未知部分，忽略或处理其他部分
                            break;
                    }
                }
            }

            return dataFile;
        }
    }
}
